package com.cx.base.day19_thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * @Author: robert.song
 * @Date: Created in 2021/11/26
 */
@Slf4j
public class Thread_13_4_原子性_可标记原子引用 {
    public static void main(String[] args) throws InterruptedException {
        GarbageBag bag = new GarbageBag("装满了垃圾袋");
        AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference(bag, true);
        log.info("start...");
        GarbageBag prev = ref.getReference();
        log.info(prev.toString());
        // 创建一个可缓存线程池
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        // 保洁阿姨上午趁你不在家换了垃圾袋
        cachedThreadPool.execute(new Runnable() {
            public void run() {
                boolean success = ref.compareAndSet(prev, new GarbageBag("空垃圾袋"), true, false);
                log.info("换了么？" + (success ? "换好了" : "没有，上午换了"));
                log.info(ref.getReference().toString());
            }
        });

        Thread.sleep(5);
        boolean success = ref.compareAndSet(prev, new GarbageBag("空垃圾袋"), true, false);
        log.info("换了么？" + (success ? "换好了" : "没有，上午保洁阿姨换了"));
        log.info(ref.getReference().toString());
    }
}

class GarbageBag {

    private String state;

    public GarbageBag(String str) {
        this.state = str;
    }

    @Override
    public String toString() {
        return "GarbageBag{" +
                "state='" + state + '\'' +
                '}';
    }
}
